//
//  BKAlertView.m
//  JKAlertDialog
//
//  Created by windcould on 16/7/5.
//  Copyright © 2016年 www.skyfox.org. All rights reserved.
//

#define AlertPadding 10
#define MenuHeight 44

#define AlertHeight 130
#define AlertWidth 270

#define RgbColor(r, g, b)       [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]
#define BtnRed 98/255.0
#define BtnGreen 201/255.0
#define BtnBlue 11/255.0
#import "BKAlertView.h"
#import "BKMyCommon.h"
#import "BKUserUnitRequestAPI.h"
@implementation BKAlertViewItem
@end

@implementation BKAlertView




/**
 *  @param title   标题
 *  @param message Btn
 *

 */
- (instancetype)initWithTitle:(NSString *)title
                      BtnMessage:(NSString *)message{
    self = [super init];
    if (self) {
        _items = [[NSMutableArray alloc] init];
        _title  = title;
        _message = message;
        [self BK_buildViews];
    }
    return self;
}

-(void)BK_buildViews{

    self.frame = CGRectMake(0, -[UIScreen mainScreen].bounds.size.height / 9, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    _coverView = [[UIView alloc]initWithFrame:[self topView].bounds];
    _coverView.backgroundColor = [UIColor blackColor];
    _coverView.alpha = 0;
    _coverView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [[self topView] addSubview:_coverView];
    
    _alertView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, AlertWidth, AlertHeight)];
    _alertView.center = CGPointMake(0,0);
    _alertView.layer.cornerRadius = 5;
    _alertView.layer.masksToBounds = YES;
    _alertView.backgroundColor = [UIColor whiteColor];
    
    [self addSubview:_alertView];
    
    //title
    CGFloat labelHeigh = [self heightWithString:_title fontSize:17 width:AlertWidth-2*AlertPadding];
    
    _labelTitle = [[UILabel alloc]initWithFrame:CGRectMake(AlertPadding, AlertPadding, AlertWidth-2*AlertPadding, labelHeigh)];

    [_labelTitle setFont:[UIFont systemFontOfSize:14]];

    _labelTitle.textColor = [UIColor blackColor];
    _labelTitle.textAlignment = NSTextAlignmentCenter;
    _labelTitle.numberOfLines = 0;
    _labelTitle.text = _title;
    _labelTitle.lineBreakMode = NSLineBreakByCharWrapping;
    [_alertView addSubview:_labelTitle];
    
    //message

    _contentScrollView = [[UIScrollView alloc]initWithFrame:CGRectZero];
    [_alertView addSubview:_contentScrollView];
    
    
    _bk_textField=[[UITextField alloc]init];
    _bk_textField.backgroundColor=[UIColor whiteColor];
    [_bk_textField setBorderStyle:UITextBorderStyleNone];
    
    _bk_textField.layer.borderColor = RGBACOLOR(221, 221, 221,1).CGColor;
    
    _bk_textField.layer.borderWidth = 1.0;
    _bk_textField.layer.cornerRadius = 5;    
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 5, 15)];
    view.backgroundColor = [UIColor whiteColor];
    _bk_textField.leftView = view;
    _bk_textField.leftViewMode = UITextFieldViewModeAlways;
    _bk_textField.textColor = BK_MY_COLOR_08;
    
    _bk_textField.textAlignment = NSTextAlignmentLeft;
    
    _bk_textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [_bk_textField setFont:[UIFont systemFontOfSize:14.0f]];
    _bk_textField.placeholder = @"请输入图片验证码";
    _bk_textField.autocorrectionType = UITextAutocorrectionTypeNo;
    _bk_textField.frame=CGRectMake(AlertPadding, AlertPadding+labelHeigh+10, AlertWidth-100, 30);
    [_alertView addSubview:_bk_textField];
    
    _btn_send=[[UIButton alloc]init];
    _btn_send.backgroundColor=[UIColor whiteColor];
    _btn_send.layer.cornerRadius = 5;
     _btn_send.layer.borderWidth = 1.0;
    _btn_send.layer.borderColor = RGBACOLOR(221, 221, 221,1).CGColor;
    [_btn_send addTarget:self action:@selector(getCodeTouched) forControlEvents:UIControlEventTouchUpInside];
    _btn_send.frame=CGRectMake(CGRectGetMaxX(_bk_textField.frame)+10, AlertPadding+labelHeigh+10, 70, 30);
    [_alertView addSubview:_btn_send];
    
    UIView *colorView = [UIView new];
    colorView.backgroundColor = RgbColor(25, 180, 142);
    colorView.frame = CGRectMake(0, AlertHeight - 40 , _alertView.frame.size.width, 1);
    [_alertView addSubview:colorView];

    
}
#pragma - 获取验证码按钮

-(void) getCodeTouched{
   NSString *uuid = [self applyforVerifyCode];//刷新验证码
      [[NSNotificationCenter defaultCenter]postNotificationName:@"getCode" object:uuid];
}
#pragma mark 申请验证码接口
-(NSString *)applyforVerifyCode{
    NSString *uuid = [BKUserUnitRequestAPI getUserImgCodeAndUniqueIdWithBlock:^(id obj, NSError *error) {
        
        if (obj == nil) {
            
            [_btn_send setImage:[UIImage imageNamed:@"BK_My_button_ refurbish_"] forState:UIControlStateNormal];
        }
        else{
            
            NSDictionary * dataDict = obj;
            [_btn_send setImage:[UIImage imageWithData:dataDict[@"data"]] forState:UIControlStateNormal];
        }
        
    }];
    
   return uuid;
}

- (void)dealloc
{
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)layoutSubviews{
    
    _buttonScrollView.frame = CGRectMake(0, _alertView.frame.size.height-MenuHeight,_alertView.frame.size.width, MenuHeight);
    _contentScrollView.frame = CGRectMake(0, _labelTitle.frame.origin.y+_labelTitle.frame.size.height, _alertView.frame.size.width, _alertView.frame.size.height-MenuHeight);
    self.contentView.frame = CGRectMake(0,0,self.contentView.frame.size.width, self.contentView.frame.size.height);
    _contentScrollView.contentSize = self.contentView.frame.size;
    
}
-(void)willMoveToSuperview:(UIView *)newSuperview
{
    [self addButtonItem];
    [_contentScrollView addSubview:self.contentView];
    [self reLayout];
}
-(void)reLayout{
    CGFloat plus;
    if (self.contentView) {
        plus = self.contentView.frame.size.height-(_alertView.frame.size.height-MenuHeight);
    }else{
        plus = _labelmessage.frame.origin.y+_labelmessage.frame.size.height -(_alertView.frame.size.height-MenuHeight);
    }
    plus = MAX(0, plus);
    CGFloat height =  MIN([self screenBounds].size.height-MenuHeight,_alertView.frame.size.height+plus);
    
    _alertView.frame = CGRectMake(_alertView.frame.origin.x, _alertView.frame.origin.y, AlertWidth, height);
    _alertView.center = self.center;
    [self setNeedsDisplay];
    [self setNeedsLayout];
}
- (CGFloat)heightWithString:(NSString*)string fontSize:(CGFloat)fontSize width:(CGFloat)width
{
    NSDictionary *attrs = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
    return  [string boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attrs context:nil].size.height;
}
#pragma mark - add item

- (NSInteger)addButtonWithTitle:(NSString *)title{
    BKAlertViewItem *item = [[BKAlertViewItem alloc] init];
    item.title = title;
    item.action =  ^(BKAlertViewItem *item) {
        NSLog(@"no action");
    };
    item.type = Button_OK;
    [_items addObject:item];
    return [_items indexOfObject:title];
}
- (void)addButton:(ButtonType)type withTitle:(NSString *)title handler:(BKAlertHandler)handler{
    BKAlertViewItem *item = [[BKAlertViewItem alloc] init];
    item.title = title;
    item.action = handler;
    item.type = type;
    [_items addObject:item];
    item.tag = [_items indexOfObject:item];
}
- (void)addButtonItem {
    
    _buttonScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _alertView.frame.size.height- MenuHeight,AlertWidth, MenuHeight)];
    _buttonScrollView.bounces = NO;
    _buttonScrollView.showsHorizontalScrollIndicator = NO;
    _buttonScrollView.showsVerticalScrollIndicator =  NO;
    CGFloat  width;
    if(self.buttonWidth){
        width = self.buttonWidth;
        _buttonScrollView.contentSize = CGSizeMake(width*[_items count], MenuHeight);
    }else
    {
        if (_items.count == 1) {
            
            width = _alertView.frame.size.width / 2;
            
        }else{
            
            width = _alertView.frame.size.width/[_items count];
            
        }
        
    }
    
    [_items enumerateObjectsUsingBlock:^(BKAlertViewItem *item, NSUInteger idx, BOOL *stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        if (_items.count == 1) {
            button.frame = CGRectMake(0,5, _alertView.frame.size.width, MenuHeight-5);
            
        }else{
            button.frame = CGRectMake(idx*width+15,0, width-30, MenuHeight-5);
        }
        
        button.layer.shadowOffset = CGSizeZero;
        button.layer.cornerRadius = 5;
        button.layer.borderWidth = 1;
        
        
        button.tag = 90000+ idx;
        if (idx==1) {
            button.layer.borderColor =[[UIColor whiteColor] CGColor];
            button.backgroundColor = RgbColor(25, 180, 142);
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }else
        {
            button.layer.borderColor =[[UIColor clearColor] CGColor];
//            button.backgroundColor = RgbColor(25, 180, 142);
            button.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:RgbColor(25, 180, 142) forState:UIControlStateNormal];

        }
        // title
        [button setTitle:item.title forState:UIControlStateNormal];
        [button setTitle:item.title forState:UIControlStateSelected];
//        button.titleLabel.font = [UIFont boldSystemFontOfSize:button.titleLabel.font.pointSize];
        button.titleLabel.font = [UIFont systemFontOfSize:14];

        
        // action
        [button addTarget:self
                   action:@selector(buttonTouched:)
         forControlEvents:UIControlEventTouchUpInside];
        
        [_buttonScrollView addSubview:button];
    }];
    [_alertView addSubview:_buttonScrollView];
    
}

- (void)buttonTouched:(UIButton*)button{
    BKAlertViewItem *item = _items[button.tag-90000];
    if (item.action) {
        item.action(item);
    }
    [self dismiss];
}
#pragma mark - show and dismiss
-(UIView*)topView{
    
    return  [[[UIApplication sharedApplication] delegate] window];
}

- (void)show {
    [UIView animateWithDuration:0.5 animations:^{
        _coverView.alpha = 0.5;
    } completion:^(BOOL finished) {
    }];
    NSString *uuid = [self applyforVerifyCode];//刷新验证码
    [[NSNotificationCenter defaultCenter]postNotificationName:@"getCode" object:uuid];
    [[self topView] addSubview:self];
    [self showAnimation];
}

- (void)dismiss {
    [self hideAnimation];
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
  
}

- (void)showAnimation {
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.4;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.2f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [_alertView.layer addAnimation:popAnimation forKey:nil];
}
- (void)hideAnimation{
    [UIView animateWithDuration:0.4 animations:^{
        _coverView.alpha = 0.0;
        _alertView.alpha = 0.0;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
#pragma mark - Handle device orientation changes
- (void)deviceOrientationDidChange: (NSNotification *)notification{
    self.frame = [self screenBounds];
    [UIView animateWithDuration:0.2f delay:0.0 options:UIViewAnimationOptionTransitionNone
                     animations:^{
                         [self reLayout];
                     }
                     completion:nil
     ];
}
- (CGRect)screenBounds{
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    // On iOS7, screen width and height doesn't automatically follow orientation
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
        if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
            CGFloat tmp = screenWidth;
            screenWidth = screenHeight;
            screenHeight = tmp;
        }
    }
    return CGRectMake(0, 0, screenWidth, screenHeight);
}
@end
